package com.tsd.core.utils;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName: ShortUrlUtil
 * @Description: 短链接工具类
 * @Author: Hillpool
 * @Date: 2022/12/7 15:42
 * @Version: 1.0
 */
public class ShortUrlUtil {

    public static void main(String[] args) {
        System.out.println(generate("demo@dts_goods@direct_wx_mini@1"));
        System.out.println(generate("demo@dts_goods@direct_wx_mini@2"));
    }

    public static String generate(String longUrl) {
        HashFunction function = Hashing.murmur3_32_fixed();
        HashCode hashCode = function.hashString(longUrl, StandardCharsets.UTF_8);
        int i = Math.abs(hashCode.asInt());
        return encode(i);
    }

    //将目标转换为62进制 位数更短
    private static String encode(long num) {
        String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        int scale = 62;
        StringBuilder sb = new StringBuilder();
        int remainder = 0;
        while (num > scale - 1) {
            remainder = Long.valueOf(num % scale).intValue();
            sb.append(chars.charAt(remainder));
            num = num / scale;
        }
        sb.append(chars.charAt(Long.valueOf(num).intValue()));
        return sb.reverse().toString();
    }
}
